import EndPageQuestion from '@/components/question/end-page-question';
import MapQuestion from '@/components/question/map-question';
import MultipleChoiceQuestion from '@/components/question/multiple-choice-question';
import PagingQuestion from '@/components/question/paging-question';
import ParagraphQuestion from '@/components/question/paragraph-question';
import ScaleQuestion from '@/components/question/scale-question';
import ShortAnswerQuestion from '@/components/question/short-answer-question';
import SingleChoiceQuestion from '@/components/question/single-choice-question';
import StartPageQuestion from '@/components/question/start-page-question';
import { QuestionProperType, QuestionType } from '@/components/question/typing';
import router from '@/router';
import useQuestionnaireStore from '@/store/questionnaire';
import { Icon } from '@iconify/vue';
import { Button, Empty, Space } from 'ant-design-vue';
import { AnyObject } from 'ant-design-vue/es/_util/type';
import { defineComponent, h, reactive, ref, VNode } from 'vue';
// import { useRoute } from 'vue-router';
import './style.css';

const questionComponents: AnyObject = {
  single: SingleChoiceQuestion,
  multiple: MultipleChoiceQuestion,
  map: MapQuestion,
  scale: ScaleQuestion,
  answer: ShortAnswerQuestion,
  paragraph: ParagraphQuestion,
  paging: PagingQuestion,
  startPage: StartPageQuestion,
  endPage: EndPageQuestion,
};

export default defineComponent({
  props: {
    questions: Array<QuestionType>,
  },
  emits: ['questionClick'],
  setup(props, { emit }) {
    const { questions } = props;
    const questionnaireStore = useQuestionnaireStore();
    const basicInfoRef = ref(questionnaireStore.getBasicInfo);
    const activeQuestion = ref<QuestionType>(
      questions && questions.length > 0 ? questions[0] : ({} as QuestionType),
    );
    const showQuestionAttributepanel = ref(false);
    // const route = useRoute();
    // const status = route.params.status;

    const questionClick = (question: any, index: number) => {
      activeQuestion.value = question;
      basicInfoRef.value.activeQuestionIndex = index;
      showQuestionAttributepanel.value = true;

      emit('questionClick', question, index);
    };

    const removeQuestion = (index: number) => {
      questions?.splice(index, 1);
      basicInfoRef.value.activeQuestionIndex = index - 1 < 0 ? 0 : index - 1;
      if (questions?.length && questions.length > 0) {
        activeQuestion.value = questions[basicInfoRef.value.activeQuestionIndex];
      } else {
        activeQuestion.value = {} as QuestionType;
        basicInfoRef.value.activeQuestionIndex = -1;
      }
    };

    const createQuestionComponent = (question: QuestionType, index: number): VNode => {
      basicInfoRef.value = questionnaireStore.getBasicInfo;

      const componentType = question.type;
      const component: VNode = questionComponents[componentType];
      if (!component) {
        throw new Error('题目类型不存在, 无法创建题目组件!');
      }
      const questionProper: QuestionProperType | undefined =
        question.activeDesignLanguage === 'zh'
          ? question.questionProperZh
          : question.questionProperEn;

      const componentProps: any = reactive({
        title: questionProper?.title,
        mode: 'design',
      });

      const hasOptionsComponent = ['single', 'multiple'];
      if (hasOptionsComponent.includes(componentType)) {
        componentProps.options = questionProper?.items?.map(eachQuestionItem => {
          return {
            label: eachQuestionItem.title,
            value: eachQuestionItem.value,
          };
        });
      }

      return (
        <div class="question-design-item">
          <component
            class={{ 'active-question': index === basicInfoRef.value.activeQuestionIndex }}
            key={`${question.activeDesignLanguage}-${question.key}`}
            language={question.activeDesignLanguage}
            question={question}
            onClick={() => questionClick(question, index)}
          />
          <div
            class={{
              'question-design-item-shotcut-button': true,
              'not-display-shotcut-button': index !== basicInfoRef.value.activeQuestionIndex,
            }}
          >
            <Button
              shape="circle"
              icon={h(
                <Icon
                  icon="material-symbols-light:delete-outline"
                  class="question-design-item-shotcut-button-icon"
                />,
              )}
              onClick={() => removeQuestion(index)}
            ></Button>
          </div>
        </div>
      );
    };

    return () => {
      return (
        <div class="design-question-design-panel">
          {questions?.length && questions.length > 0 ? (
            questions?.map((eachQuestion, index) => {
              return createQuestionComponent(eachQuestion, index);
            })
          ) : (
            <Empty />
          )}
          {questions?.length && questions.length > 0 ? (
            <div class="operate-buttons">
              <Space>
                <Button onClick={() => router.push({ path: '/questionnaire/basic-info' })}>
                  上一步
                </Button>
                <Button type="primary">保存</Button>
              </Space>
            </div>
          ) : (
            <div class="operate-buttons">
              <Space>
                <Button onClick={() => router.push({ path: '/questionnaire/basic-info' })}>
                  上一步
                </Button>
              </Space>
            </div>
          )}
        </div>
      );
    };
  },
});
